package com.lzj.server.common.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.lzj.server.common.service.MailService;
import com.lzj.server.constant.RedisConstant;
import com.lzj.server.exceptions.BaseException;
import com.lzj.server.utils.RedisUtils;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SmtpMailServiceImpl implements MailService {

    @Resource
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String fromName;
    private SimpleMailMessage message;

    @Override
    public void sendEmailCaptcha(String toEmail) {
        String subject = "邮箱验证码";
        String code = RandomUtil.randomNumbers(6);
        RedisUtils.set(RedisConstant.EMAIL_CODE + toEmail, code, 5, TimeUnit.MINUTES);
        String body = "【系统服务】您的验证码是：" + code + "，5分钟内有效，请勿泄露。";
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(toEmail);
            message.setSubject(subject);
            message.setText(body);
            message.setFrom(fromName);

            mailSender.send(message);
            log.info("邮件验证码已成功发送至：{}", toEmail);
        } catch (Exception e) {
            log.error("发送邮件验证码失败，收件人：{}，错误信息：{}", toEmail, e.getMessage(), e);
            throw new BaseException(500, "邮件发送失败，请稍后重试");
        }
    }
}
